<template>
  <div class="app-container" v-loading="Loading">
    <div class="tab-bar">
      <div
        class="tab-item"
        :class="current === it.id ? 'tab-item-ac' : ''"
        v-for="(it, idx) in customerTabList"
        :key="idx"
        @click="handleTabClick(it.id)"
      >
        {{ it.name }}
      </div>
    </div>

    <div class="form-main" ref="formMain">
      <el-form
        :model="form"
        ref="formRef"
        :rules="rules"
        style="margin-top: 30px"
      >
        <div ref="customer">
          <el-card class="box-card">
            <div slot="header" class="clearfix">客户信息</div>

            <el-form-item
              label="公司名称"
              prop="enterpriseInfo.taxpayerName"
              label-width="120px"
              clearable
            >
              <el-input
                placeholder="请输公司名称"
                clearable
                disabled
                maxlength="200"
                style="width: 500px"
                v-model="form.enterpriseInfo.taxpayerName"
              />
            </el-form-item>
            <el-form-item
              label="所属省份"
              prop="enterpriseInfo.provinceId"
              label-width="120px"
            >
              <el-select
                clearable
                disabled
                v-model="form.enterpriseInfo.provinceId"
                placeholder="请选择省份"
                style="width: 500px"
              >
                <el-option
                  v-for="item in ProvinceList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="税号"
              clearable
              maxlength="200"
              prop="enterpriseInfo.creditCode"
              label-width="120px"
            >
              <el-input
                clearable
                disabled
                placeholder="请输入企业税号"
                style="width: 500px"
                v-model="form.enterpriseInfo.creditCode"
              />
            </el-form-item>
            <el-form-item
              label="税务密码"
              prop="enterpriseInfo.password"
              label-width="120px"
            >
              <el-input
                clearable
                disabled
                maxlength="200"
                placeholder="请输入税务密码"
                style="width: 500px"
                v-model="form.enterpriseInfo.password"
              />
            </el-form-item>
            <el-form-item
              label="法人"
              prop="enterpriseInfo.legalPerson"
              label-width="120px"
            >
              <el-input
                clearable
                disabled
                maxlength="200"
                placeholder="请输入法人姓名"
                style="width: 500px"
                v-model="form.enterpriseInfo.legalPerson"
              />
            </el-form-item>
            <!-- <el-form-item label="公司占比" label-width="120px">
              <el-input
                clearable
                disabled
                maxlength="200"
                placeholder="请输入公司占比"
                style="width: 500px"
                type="number"
                min="0"
                v-model="form.enterpriseInfo.legalPersonRatio"
              >
                <template slot="suffix"
                  ><span style="color: #000">%</span></template
                >
              </el-input>
            </el-form-item> -->
            <el-form-item
              label="联系方式"
              prop="enterpriseInfo.phone"
              label-width="120px"
            >
              <el-input
                clearable
                disabled
                placeholder="请输入联系人"
                style="width: 500px"
                maxlength="11"
                v-model="form.enterpriseInfo.phone"
              />
            </el-form-item>
            <div v-for="(it, idx) in form.shareholderList" :key="idx">
              <el-form-item :label="`股东${idx + 1}`" label-width="120px">
                <el-input
                  disabled
                  clearable
                  placeholder="请输入股东"
                  maxlength="200"
                  style="width: 500px"
                  v-model="it.realname"
                />
              </el-form-item>

              <el-form-item label="公司占比" label-width="120px">
                <el-input
                  disabled
                  clearable
                  style="width: 500px"
                  maxlength="200"
                  placeholder="请输入公司占比"
                  v-model="it.companyRatio"
                >
                  <template slot="suffix"
                    ><span style="color: #000">%</span></template
                  >
                </el-input>
              </el-form-item>
              <el-form-item label="联系方式" label-width="120px">
                <el-input
                  clearable
                  disabled
                  style="width: 500px"
                  placeholder="请输入联系方式"
                  maxlength="11"
                  v-model="it.phone"
                ></el-input>
              </el-form-item>
              <el-form-item label="个人负债" label-width="120px">
                <el-input
                  clearable
                  disabled
                  style="width: 500px"
                  maxlength="200"
                  placeholder="请输入个人负债"
                  v-model="it.personalDebt"
                ></el-input>
              </el-form-item>
            </div>
          </el-card>
        </div>
        <div ref="basicInfo">
          <el-card class="box-card">
            <div slot="header" class="clearfix">基本信息</div>
            <el-form-item
              label="客户经理"
              label-width="120px"
              prop="managerIds"
            >
              <el-select
                disabled
                clearable
                style="width: 500px"
                v-model="form.managerIds"
                filterable
                placeholder="请选择客户经理"
              >
                <el-option
                  v-for="item in managerList"
                  :key="item.id"
                  :label="item.name + ' ' + '(' + item.phone + ')'"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="办理业务员" label-width="120px">
              <el-select
                clearable
                style="width: 500px"
                v-model="form.salesmanIds"
                filterable
                multiple
                placeholder="请选择办理业务员"
              >
                <el-option
                  v-for="item in salesmanList"
                  :key="item.id"
                  :label="item.name + ' ' + '(' + item.phone + ')'"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="财务联系人" label-width="120px">
              <el-input
                clearable
                maxlength="20"
                placeholder="请输入财务联系人"
                style="width: 500px"
                v-model="form.financeUser"
              />
            </el-form-item>
            <el-form-item
              v-if="form.financeUser"
              label="财务联系人方式"
              label-width="120px"
              prop="financePhone"
            >
              <el-input
                clearable
                placeholder="请输入财务联系电话号码"
                style="width: 500px"
                maxlength="11"
                v-model="form.financePhone"
              />
            </el-form-item>
            <el-form-item label="企业注册日期" label-width="120px">
              <el-date-picker
                clearable
                v-model="form.registerTime"
                type="date"
                placeholder="选择日期"
                style="width: 500px"
                value-format="yyyy-MM-dd"
                format="yyyy 年 MM 月 dd 日"
              />
            </el-form-item>
            <el-form-item label="一般户" label-width="120px">
              <el-input
                clearable
                placeholder="请输入一般户"
                style="width: 500px"
                maxlength="200"
                v-model="form.normalAccount"
              />
            </el-form-item>
            <el-form-item label="基本户" label-width="120px">
              <el-input
                clearable
                maxlength="200"
                placeholder="请输入基本户"
                style="width: 500px"
                v-model="form.basicAccount"
              />
            </el-form-item>
          </el-card>
        </div>
        <div ref="customerTax">
          <el-card class="box-card">
            <div slot="header" class="clearfix">客户征信</div>
            <el-form-item label="企业负债" label-width="120px">
              <el-input
                type="textarea"
                clearable
                style="width: 500px"
                placeholder="请输入"
                maxlength="200"
                show-word-limit
                v-model="form.creditEnterpriseLiability"
              ></el-input>
            </el-form-item>
            <el-form-item label="个人负债" label-width="120px">
              <el-input
                type="textarea"
                clearable
                style="width: 500px"
                placeholder="请输入"
                show-word-limit
                maxlength="200"
                v-model="form.creditIndividualLiability"
              ></el-input>
            </el-form-item>
            <el-form-item label="近3月查询" label-width="120px">
              <el-input
                type="textarea"
                clearable
                style="width: 500px"
                placeholder="请输入"
                maxlength="200"
                show-word-limit
                v-model="form.creditNearlyMarch"
              ></el-input>
            </el-form-item>
          </el-card>
        </div>
        <div ref="companyMsg">
          <el-card class="box-card">
            <div slot="header" class="clearfix">公司主营</div>
            <div v-for="(v, idx) in form.businessUpstream" :key="idx + '0'">
              <el-form-item
                :label="`上游 / 价格${idx + 1}`"
                label-width="120px"
              >
                <el-input
                  type="textarea"
                  clearable
                  placeholder="请输入"
                  style="width: 500px"
                  maxlength="200"
                  show-word-limit
                  v-model="v.content"
                />
                <el-button
                  size="mini"
                  type="primary"
                  @click="addDownList(idx)"
                  v-if="idx === 0"
                  >添加</el-button
                >
                <el-button
                  size="mini"
                  @click="delDownList(idx)"
                  v-if="idx !== 0"
                  >删除</el-button
                >
              </el-form-item>
            </div>
            <div v-for="(v2, idx) in form.businessDownstream" :key="idx + '1'">
              <el-form-item
                :label="`下游 / 价格${idx + 1}`"
                label-width="120px"
              >
                <el-input
                  type="textarea"
                  clearable
                  placeholder="请输入"
                  show-word-limit
                  style="width: 500px"
                  maxlength="200"
                  v-model="v2.content"
                />
                <el-button
                  size="mini"
                  type="primary"
                  @click="addUpList(idx)"
                  v-if="idx === 0"
                  >添加</el-button
                >
                <el-button size="mini" @click="delUpList(idx)" v-if="idx !== 0"
                  >删除</el-button
                >
              </el-form-item>
            </div>
          </el-card>
        </div>
        <div ref="otherInfo">
          <el-card class="box-card">
            <div slot="header" class="clearfix">补充信息</div>
            <el-form-item label="客户诉求" label-width="120px">
              <el-input
                type="textarea"
                clearable
                style="width: 500px"
                placeholder="请输入"
                maxlength="200"
                show-word-limit
                v-model="form.customerDemands"
              ></el-input>
            </el-form-item>
            <el-form-item label="情况概括" label-width="120px">
              <el-input
                type="textarea"
                clearable
                style="width: 500px"
                placeholder="请输入"
                maxlength="200"
                show-word-limit
                v-model="form.situationOverview"
              ></el-input>
            </el-form-item>
          </el-card>
        </div>
        <div ref="communicationHistory">
          <el-card class="box-card">
            <div slot="header" class="clearfix">沟通历史记录</div>
            <div>
              <history-list :key="listkey" :id="$route.query.id" />
            </div>
          </el-card>
        </div>
      </el-form>
    </div>

    <el-backtop target=".form-main" :bottom="100" :visibility-height="1000">
      <div
        style="
           {
            height: 100%;
            width: 100%;
            background-color: #ccc;
            box-shadow: 0 0 6px rgba(0, 0, 0, 0.12);
            text-align: center;
            line-height: 40px;
            border-radius: 20px;
            color: #1989fa;
          }
        "
      >
        <i style="color: #fff;" class="el-icon-upload2"></i>
      </div>
    </el-backtop>

    <div
      style="
        background-color: #fff;
        width: 100%;
        height: 60px;
        padding-bottom: 20px;
      "
    >
      <div
        style="
          margin: 20px;
          position: absolute;
          bottom: -10px;
          left: 50%;
          transform: translate(-50%, 0);
        "
      >
        <el-button
          style="width: 150px"
          type="primary"
          @click="submitForm('formRef')"
          >提交</el-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import { customerTabList, campanyRules } from "../options";
import { getProvinceList } from "@/api/tax";
import { getUserList } from "@/api/dept";
import historyList from "./components/historyList.vue";
import {
  companyRrecord,
  companyRecordCreate,
  getCustomerManagerList,
  companyRecordList
} from "@/api/customer";
import { getsalesmanList } from "../../../api/customer";
const form = {
  enterpriseInfo: {
    taxpayerName: null,
    provinceId: null,
    creditCode: null,
    password: null,
    legalPerson: null,
    legalPersonRatio: null,
    phone: null
  },
  adminId: null,
  salesmanIds: null,
  financeUser: null,
  financePhone: null,
  registerTime: null,
  normalAccount: null,
  basicAccount: null,
  shareholderList: null,
  creditEnterpriseLiability: null, //企业负债
  creditIndividualLiability: null, //个人负债
  creditNearlyMarch: null,
  businessUpstream: [{ content: null }], //上游/价格
  businessDownstream: [{ content: null }], //下游/价格
  customerDemands: null, //客户诉求
  situationOverview: null,
  managerIds: null,
  companyId: null,
  id: null
};
export default {
  name: "communicate",
  components: {
    historyList
  },
  data() {
    return {
      Loading: true,
      current: 0,
      customerTabList,
      form: Object.assign({}, form),
      ProvinceList: [],
      rules: campanyRules,
      managerList: [], //客户经理列表
      salesmanList: [], //销售员列表
      listkey: 1
    };
  },
  mounted() {
    // 监听滚动事件，更新选中的标签
    window.addEventListener("scroll", this.handleScroll);
  },
  beforeDestroy() {
    // 移除滚动事件监听
    window.removeEventListener("scroll", this.handleScroll);
  },
  async created() {
    await this.getProvince();
    await this.getUserList();
    await this.getSalesmanList();
    if (this.$route.query.id) {
      await this.getDetail(this.$route.query.id);
      this.listkey++;
    }
    // this.restForm();
  },
  methods: {
    submitForm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const form = Object.assign({}, this.form);
          let params = {
            companyId: form.companyId,
            registerTime: form.registerTime,
            financeUser: form.financeUser,
            financePhone: form.financePhone,
            basicAccount: form.basicAccount,
            normalAccount: form.normalAccount,
            customerDemands: form.customerDemands,
            situationOverview: form.situationOverview,
            creditEnterpriseLiability: form.creditEnterpriseLiability,
            creditIndividualLiability: form.creditIndividualLiability,
            creditNearlyMarch: form.creditNearlyMarch,
            businessUpstream: JSON.stringify(form.businessUpstream),
            businessDownstream: JSON.stringify(form.businessDownstream),
            salesmanIds: form.salesmanIds.join(",")
          };
          console.log(params);
          // return
          companyRecordCreate(params).then(res => {
            this.$message({
              message: "提交成功",
              type: "success"
            });
            this.getDetail(form.companyId);
            this.listkey = this.listkey + 1;
          });

          // this.$message({
          //   message: "提交成功",
          //   type: "success"
          // });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getDetail(id) {
      companyRrecord(id)
        .then(res => {
          console.log(res);
          res.data.salesmanIds = res.data.salesmanIds
            ? res.data.salesmanIds.split(",")
            : [];
          if (res.data.businessUpstream == null) {
            res.data.businessUpstream = [{ content: null }];
          } else {
            res.data.businessUpstream = JSON.parse(res.data.businessUpstream);
          }
          if (res.data.businessDownstream == null) {
            res.data.businessDownstream = [{ content: null }];
          } else {
            res.data.businessDownstream = JSON.parse(
              res.data.businessDownstream
            );
          }
          this.form = Object.assign(this.form, res.data);
          console.log("this.form", this.form);
          this.Loading = false;
        })
        .finally(() => {
          this.Loading = false;
        });
    },
    addDownList() {
      this.form.businessUpstream.push({ content: "" });
    },
    delDownList(idx) {
      this.form.businessUpstream.splice(idx, 1);
    },
    addUpList() {
      this.form.businessDownstream.push({ content: "" });
    },
    delUpList(idx) {
      this.form.businessDownstream.splice(idx, 1);
    },
    // 获取客户经理
    getUserList() {
      getCustomerManagerList().then(res => {
        this.managerList = res.data.map(v => {
          return {
            name: v.nickName,
            id: v.adminId,
            phone: v.phoneNumber
          };
        });
      });
    },
    // 获取销售员
    getSalesmanList() {
      getsalesmanList().then(res => {
        this.salesmanList = res.data.map(v => {
          return {
            name: v.nickName,
            id: v.adminId,
            phone: v.phoneNumber
          };
        });
      });
    },
    // 获取地区列表
    getProvince() {
      getProvinceList().then(res => {
        this.ProvinceList = res.data;
      });
    },
    handleTabClick(id) {
      this.current = id;
      const mapObj = {
        0: "customer",
        1: "basicInfo",
        2: "customerTax",
        3: "companyMsg",
        4: "otherInfo",
        5: "communicationHistory"
      };
      this.$refs[mapObj[id]].scrollIntoView({ behavior: "smooth" });
    },
    handleScroll() {
      const mapObj = {
        0: "customer",
        1: "basicInfo",
        2: "customerTax",
        3: "companyMsg",
        4: "otherInfo",
        5: "communicationHistory"
      };
      console.log("kkk");
      // 计算当前滚动位置
      const scrollPosition = window.scrollY || window.pageYOffset;

      // 检查每个内容区域是否在视口中
      for (const id in mapObj) {
        const ref = this.$refs[mapObj[id]];
        if (ref) {
          const rect = ref.getBoundingClientRect();

          // 判断内容区域顶部在视口内且底部不超出视口
          if (
            rect.top >= 0 &&
            rect.top <= window.innerHeight &&
            rect.bottom <= window.innerHeight
          ) {
            this.current = parseInt(id, 10);
            break; // 找到第一个符合条件的即可
          }
        }
      }
    }
  },
  submitForm() {}
};
</script>

<style scoped lang="scss">
.app-container {
  height: calc(100vh - 50px);
  background-color: #f5f5f5;
  position: relative;
}
.tab-bar {
  position: absolute;
  left: 10px;
  top: 0px;
  width: calc(100% - 20px);
  background-color: #fff;
  height: 60px;
  line-height: 60px;
  display: flex;
  .tab-item {
    height: 100%;
    width: 100px;
    text-align: center;
    font-size: 14px;
  }
  .tab-item-ac {
    background-color: rgba(64, 158, 255, 0.1);
    color: #409eff;
    border-top: 2px solid #409eff;
  }
}

.form-main {
  margin-top: 40px;
  height: calc(
    100% - 80px
  ); /* 将高度设置为父级容器高度减去上方固定元素的高度 */
  overflow-y: auto;
  // overflow: scroll;
  .form-box {
    text-align: center;
    margin-top: 40px;
  }
  .uploadPic {
    width: 90px;
    height: 90px;

    background: #eeeeee;
    border-radius: 8px;
    position: relative;
    > i {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .inputSty {
    display: flex;
  }
  .box-card {
    margin-bottom: 30px;
  }
}
</style>
